package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.DictItem;
import com.sskj.api.exception.LogicException;
import com.sskj.api.mapper.DictItemMapper;
import com.sskj.api.service.IDictItemService;
import com.sskj.api.vo.req.DictItemPageListReq;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Schema
public class DictItemService extends ServiceImpl<DictItemMapper, DictItem> implements IDictItemService {

    @Override
    public void add(DictItem dictItem) {
        LambdaQueryWrapper<DictItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DictItem::getDictId, dictItem.getDictId())
                .eq(DictItem::getKey, dictItem.getKey());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("键名已存在");
        }

        dictItem.setCreateTime(LocalDateTime.now());
        save(dictItem);
    }

    @Override
    public void deleteById(Long id) {
        removeById(id);
    }

    @Override
    public void deleteByDictId(Long dictId) {
        LambdaQueryWrapper<DictItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DictItem::getDictId, dictId);

        remove(lambdaQueryWrapper);
    }

    @Override
    public void update(DictItem dictItem) {
        LambdaQueryWrapper<DictItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(DictItem::getId, dictItem.getId())
                .eq(DictItem::getDictId, dictItem.getDictId())
                .eq(DictItem::getKey, dictItem.getKey());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("键名已存在");
        }

        dictItem.setUpdateTime(LocalDateTime.now());
        updateById(dictItem);
    }

    @Override
    public IPage<DictItem> pageList(DictItemPageListReq req) {
        IPage<DictItem> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        return baseMapper.pageList(pageConfig, req);
    }
}
